package org.pathwaycommons.nlp;

import java.util.*;

/**
 * Reads the delta features resource file and organizes the feature sets.
 */
public class DeltaFeatureReader
{
	public static final List<String> KEYWORD = Arrays.asList("phospho", "acetyl", "hydroxy",
		"ubiquitin", "methyl", "retinyl", "sumoyl", "fucosyl", "xylosyl", "palmitoleyl", "decanoyl",
		"octanoyl", "removal", "galactosyl", "glucosyl");

	public Map<String, Set<String>> readFeatureSets(boolean gained, boolean group)
	{
		// map of sets
		Map<String, Set<String>> map = new HashMap<String, Set<String>>();

		Scanner sc = new Scanner(getClass().getResourceAsStream("DeltaFeatures.txt"));

		// skip header
		sc.nextLine();

		while (sc.hasNextLine())
		{
			String[] token = sc.nextLine().split("\t");
			String source = token[0];
			String target = token[2];

			String featStr = gained ? token[5] : token[6];
			featStr = featStr.replaceAll("\\[", "").replaceAll("\\]", "");

			for (String feat : featStr.split(", "))
			{
				if (feat.isEmpty()) continue;
				if (feat.contains("@")) feat = feat.substring(0, feat.indexOf("@"));

				if (!map.containsKey(feat)) map.put(feat, new HashSet<String>());
				map.get(feat).add(source + " " + target);
			}
		}

		return group ? group(map) : map;
	}


	/**
	 * Groups features using the given substring keywords.
	 */
	private Map<String, Set<String>> group(Map<String, Set<String>> map)
	{
		Map<String, Set<String>> grouped = new HashMap<String, Set<String>>();
		for (String key : KEYWORD)
		{
			grouped.put(key, new HashSet<String>());
		}

		for (String feat : map.keySet())
		{
			for (String key : KEYWORD)
			{
				if (feat.contains(key)) grouped.get(key).addAll(map.get(feat));
			}
		}
		return grouped;
	}

	public static void main(String[] args)
	{
		DeltaFeatureReader d = new DeltaFeatureReader();
		Map<String, Set<String>> gain = d.readFeatureSets(true, false);
		Map<String, Set<String>> lost = d.readFeatureSets(false, false);

		Set<String> set = new HashSet<String>(gain.keySet());
		set.addAll(lost.keySet());
		List<String> feats = new ArrayList<String>(set);

		final Map<String, Integer> cnt = new HashMap<String, Integer>();
		for (String feat : set)
		{
			cnt.put(feat, Math.max(
				gain.containsKey(feat) ? gain.get(feat).size() : 0,
				lost.containsKey(feat) ? lost.get(feat).size() : 0));
		}

		Collections.sort(feats, new Comparator<String>()
		{
			@Override
			public int compare(String o1, String o2)
			{
				return cnt.get(o2).compareTo(cnt.get(o1));
			}
		});

		for (String feat : feats)
		{
			System.out.println(cnt.get(feat) + "\t" + feat);
		}
	}
}
